/**
* 基础菜单 角色管理
*/
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>角色管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline"  ref="formInline" class="user-search" >
      <el-form-item label="搜索：">

      <el-form-item label="" prop="roleName">
        <el-input size="small" v-model="formInline.roleName" placeholder="请输入角色名称" @keyup.enter.native="search"></el-input>
      </el-form-item>

      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button> <el-button size="small" type="primary" icon="el-icon-delete" @click="clearForm">清空</el-button>
      </el-form-item>

    </el-form>

    <el-row size="small">
      <el-button size="small" type="primary" icon="el-icon-plus" @click="addRole" v-has="'sys:role:add'">添加</el-button>
    </el-row>
    <br>

    <!-- 角色列表 -->
    <el-table size="small" @selection-change="selectChange" :data="roleData" highlight-current-row v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.1)" border element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="50">

      </el-table-column>
      <el-table-column align="center" sortable prop="roleName" label="角色名称" width="120">
      </el-table-column>
      <el-table-column align="center" sortable prop="remark" label="备注" width="240">
      </el-table-column>
      </el-table-column>
      <el-table-column align="center" sortable prop="createTime" label="创建时间" min-width="120">
      </el-table-column>
      <el-table-column align="center" sortable prop="updateTime" label="更新时间" min-width="120">
      </el-table-column>
      <el-table-column label="操作" min-width="250">
        <template slot-scope="scope">
          <el-button size="mini"  type="success"  icon="el-icon-edit" @click="editRole(scope.$index, scope.row)" v-has="'sys:role:edit'">编辑</el-button>
          <el-button size="mini"  type="danger" icon="el-icon-delete" @click="deleteRole(scope.$index, scope.row)" v-has="'sys:role:delete'" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页组件 -->
    <pagination v-bind:child-msg="pageInfo" @callFather="callFather"></pagination>

    <!-- 添加编辑界面 -->
    <el-dialog :title="title" :visible.sync="RoleFormVisible" width="30%" @click='closeDialog("edit")'>
      <el-form label-width="80px" ref="roleForm" :model="roleForm" :rules="roleFormRules">

        <el-form-item label="角色名称" prop="roleName">
          <el-input size="small" v-model="roleForm.roleName"  placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="菜单权限">
          <el-tree
            :data="menuOptions"
            show-checkbox
            default-expand-all
            ref="menu"
            node-key="id"
            empty-text="加载中，请稍后"
            :props="defaultProps"
          ></el-tree>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input size="small" v-model="roleForm.remark" placeholder="请输入备注"></el-input>
        </el-form-item>


      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>
        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('roleForm')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import pagination from '@/components/pagination'
  export default {
    data() {
      return {
        // 请求数据参数
        formInline: {
          page: 1,
          pageSize: 10,
          roleName: ''
        },
        loading: false, //是显示加载
        RoleFormVisible: false, //控制用户添加页面显示与隐藏
        title: "添加用户",
        roleData:[], // 用户列表数据
        selectData: [], // 选择数据
        roleForm:{
          roleId:'',
          roleName:'',
          remark:'',
          menuIds:[]
        },
        // 分页参数
        pageInfo: {
          currentPage: 1,
          pageSize: 10,
          total: 0
        },
        // 菜单列表
        menuOptions: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        // rules表单验证
        roleFormRules: {
          roleName: [
            { required: true, message: '请输入角色名称', trigger: 'blur' }
          ]
        },
      }
    },
    // 注册组件
    components: {
      pagination
    },
    created(){
      this.getRoleList()
    },
    methods: {
      search(){
        this.getRoleList()
      },
      clearForm(){

        if(this.$refs['formInline']){
          this.$refs['formInline'].resetFields()
        }
        this.getRoleList()
      },
      getRoleList(){
        this.loading = true;
        this.$axios.getRoleList(this.formInline).then(res=>{
          this.loading=false
          if (res.code === 0) {
            this.roleData=res.data.list;
            this.pageInfo.total=res.data.totalCount
          }

        }).catch(err=>{
          this.loading=false
          console.log("getRoleListErr",err);
        })
      },
      // 选择复选框事件
      selectChange(val) {
        this.selectData = val
        console.log('selectData',this.selectData)
      },
      editRole(index,row){
        this.RoleFormVisible = true
        this.title="编辑角色"
        this.roleForm.roleId=row.roleId
        this.roleForm.roleName=row.roleName
        this.roleForm.remark=row.remark

        this.$nextTick(() => {
          this.getRoleMenuTreeselect(row.roleId);
        });
      },
      deleteRole(index,row){
        this.$confirm('确定要删除吗?', '信息', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$axios.deleteRole({id:row.roleId}).then(res=>{
            if (res.code===0) {
              this.getRoleList()
              this.$message({
                type: 'success',
                message: '删除成功！'
              })
            }
          }).catch(err=>{
              console.log('deleteRoleErr',err)
          })
        })
      },
      // 分页插件事件
      callFather(parm) {
        this.formInline.page = parm.currentPage
        this.formInline.pageSize = parm.pageSize
        this.getUserList(this.formInline)
      },
      // 关闭编辑、增加弹出框
      closeDialog(dialog) {
        if (dialog == 'edit') {
          this.RoleFormVisible = false
        }
      },
      addRole(){
        this.RoleFormVisible = true
        this.title='添加角色'
        this.roleForm.roleId=''
        this.roleForm.roleName=''
        this.roleForm.remark=''
        this.roleForm.menuIds=[]

        if( this.$refs['roleForm']){
          this.$refs['roleForm'].resetFields()
        }
        this.getMenuTreeList();
        if (this.$refs.menu != undefined) {
          this.$refs.menu.setCheckedKeys([]);
        }
      },
      getMenuTreeList(){
        this.$axios.getMenuTreeList(this.formInline).then(res=>{
          if (res.code === 0) {
            this.menuOptions=res.data;
            console.log("menuOptions"+this.menuOptions);
          }

        }).catch(err=>{
          console.log("menuOptions",err);
        })
      },
      /** 根据角色ID查询菜单树结构 */
      getRoleMenuTreeselect(roleId) {
        this.getMenuTreeList();
        // 先清空key
        this.$refs.menu.setCheckedKeys([]);
        this.$axios.roleMenuTreeSelect({roleId:roleId}).then(res=>{
          if (res.code === 0) {
             // 再设置key
            this.$refs.menu.setCheckedKeys(res.data);
            console.log("roleMenuTreeselect:"+res.data);
          }

        }).catch(err=>{
          console.log("roleMenuTreeselect",err);
        })
      },
      // 所有菜单节点数据
      getMenuAllCheckedKeys() {
        // 目前被选中的菜单节点
        let checkedKeys = this.$refs.menu.getCheckedKeys();
        console.log("checkedKeys:",checkedKeys)
        // 半选中的菜单节点
      //  let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      //  console.log("halfCheckedKeys:",halfCheckedKeys)
     //   checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
       // console.log("checkedKeys:",checkedKeys)
        return checkedKeys;
      },
      submitForm(roleForm){
        this.$refs[roleForm].validate(valid => {

          if (valid) {
            this.loading = true
            this.roleForm.menuIds=this.getMenuAllCheckedKeys();
            // 请求方法
            if(this.roleForm.roleId){
               this.$axios.updateRole(this.roleForm).then(res=>{
                 this.loading = false
                 if (res.code===0) {
                   this.RoleFormVisible = false
                   this.getRoleList()
                   this.$message({
                     type: 'success',
                     message: '修改成功！'
                   })
                 }
               }).catch(err=>{
                 console.log('updateRoleErr',err);
                 this.loading = false
               })
            }else{
              this.$axios.saveRole(this.roleForm).then(res => {
                  this.loading = false
                  if (res.code===0) {
                    this.RoleFormVisible = false
                    this.getRoleList()
                    this.$message({
                      type: 'success',
                      message: '保存成功！'
                    })
                  }
                }).catch(err=>{
                  console.log('saveRoleErr',err);
                  this.loading = false
              })


            }
          } else {
            return false
          }
        })
      }
    }
  }
</script>

<style scoped>
  .user-search {
    margin-top: 20px;
  }
</style>


